package org.linphone.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import com.xuhao.android.libsocket.sdk.OkSocket;

import org.linphone.crash.CrashHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xiang on 2018/5/15.
 */

public class MyApplication extends Application {
	//activity列表
	private static List<Activity> activities;
	private static Context context;//全局上下文
    public static  String  crashFileName;
	@Override
	public void onCreate() {
		super.onCreate();
		context = getApplicationContext();
		OkSocket.initialize(this);

		//收集错误信息
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext(),"MyLinephoneCrash.log");

		activities = new ArrayList<>();
		registerActivityLifecycleCallbacks(callbacks);//-用于对Activity的生命周期事件进行集中处理
		/*String string_a = null;
		string_a.split(",");*/

		//init();
	}
	private ActivityLifecycleCallbacks callbacks = new ActivityLifecycleCallbacks(){

		@Override
		public void onActivityCreated(final Activity activity, Bundle bundle) {
			// 获得主线程的looper
			Looper mainLooper = getMainLooper();
			Handler handler = new Handler(mainLooper);
			handler.post(new Runnable() {
				@Override
				public void run() {
					getActivitieList().add(activity);
				}
			});
		}

		@Override
		public void onActivityStarted(Activity activity) {

		}

		@Override
		public void onActivityResumed(Activity activity) {

		}

		@Override
		public void onActivityPaused(Activity activity) {

		}

		@Override
		public void onActivityStopped(Activity activity) {

		}

		@Override
		public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

		}

		@Override
		public void onActivityDestroyed(Activity activity) {
			getActivitieList().remove(activity);
		}
	};

	public List<Activity> getActivitieList() {
		return activities;
	}

	public static void exit() {
		for (int i = activities.size() - 1; i >= 0; i--) {
			Activity activity = activities.get(i);
			if (activity != null) {
				activity.finish();
			}
		}
	}
//	private void init() {
//		XUpdate.get()
//				.debug(false) //开启debug模式，可用于问题的排查
//				.isWifiOnly(false)     //默认设置只在wifi下检查版本更新
//				.isGet(true)          //默认设置使用get请求检查版本
//				.isAutoMode(false)    //默认设置非自动模式，可根据具体使用配置
//				.param("VersionCode", UpdateUtils.getVersionCode(this)) //设置默认公共请求参数
//				.param("AppKey", getPackageName())
//				.setOnUpdateFailureListener(new OnUpdateFailureListener() { //设置版本更新出错的监听
//					@Override
//					public void onFailure(UpdateError error) {
//						//ToastUtils.toast(error.toString());
//					}
//				})
//				.setIUpdateHttpService(new OKHttpUpdateHttpService()) //这个必须设置！实现网络请求功能。
//				.init(this);   //这个必须初始化
//
//	}

	//获取全局的上下文
	public static Context getContext(){
		return context;
	}

}
